<template>
  <modal
    title="修改角色权限"
    :visible="roleEditVisiable"
    ref="editRoleModal"
    :loading="loading"
    okText="确定"
    @cancelHandler="onClose"
    @okHandler="handleSubmit"
  >
    <!-- title="新增角色"
    :visible="roleAddVisiable"
    ref="addRoleModal"
    :loading="loading"
    okText="确定"
    @cancelHandler="onClose"
    @okHandler="handleSubmit" -->
    <template v-slot:content>
      <a-form :form="form">
        <a-form-item label="角色名称" v-bind="formItemLayout">
          <!--<label v-decorator="['roleName']" />-->
          <p>{{ role.roleName }}</p>
        </a-form-item>
        <a-form-item label="角色描述" v-bind="formItemLayout">
          <!--<label v-decorator="['remark', { rules: [{ max: 50, message: '长度不能超过50个字符' }] }]"> </label>-->
          <p>{{ role.remark }}</p>
        </a-form-item>
        <a-form-item
          label="权限选择"
          style="margin-bottom: 2rem"
          :validateStatus="menuSelectStatus"
          :help="menuSelectHelp"
          v-bind="formItemLayout"
        >
          <a-tree
            :key="menuTreeKey"
            ref="menuTree"
            :checkable="true"
            :checkStrictly="checkStrictly"
            :defaultCheckedKeys="defaultCheckedKeys"
            @check="handleCheck"
            @expand="handleExpand"
            :expandedKeys="expandedKeys"
            :treeData="menuTreeData"
            style="height: 300px;overflow: auto;"
          >
          </a-tree>
        </a-form-item>
      </a-form>
    </template>
  </modal>
</template>
<script>
import modal from '~/tool/modal';
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 }
};
export default {
  name: 'RoleEdit',
  components: {
    modal
  },
  props: {
    roleEditVisiable: {
      default: false
    },
    roleInfoData: {
      require: true
    }
  },
  data() {
    return {
      menuTreeKey: +new Date(),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      menuSelectStatus: '',
      menuSelectHelp: '',
      role: {
        menuId: ''
      },
      menuTreeData: [],
      allTreeKeys: [],
      checkedKeys: [],
      defaultCheckedKeys: [],
      expandedKeys: [],
      checkStrictly: false,

      //  半选中的父节点集合
      halfCheckedKeys: []
    };
  },
  methods: {
    reset() {
      this.menuTreeKey = +new Date();
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.defaultCheckedKeys = [];
      this.menuSelectStatus = this.menuSelectHelp = '';
      this.loading = false;
      this.form.resetFields();
    },
    onClose() {
      this.$confirm({
        title: '确定放弃编辑吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk: this.onCloseConfirm
      });
    },
    onCloseConfirm() {
      this.reset();
      this.$emit('close');
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys;
    },
    closeAll() {
      this.expandedKeys = [];
    },
    enableRelate() {
      this.checkStrictly = false;
    },
    disableRelate() {
      this.checkStrictly = true;
    },
    handleCheck(checkedKeys, e) {
      console.log(checkedKeys);
      this.checkedKeys = checkedKeys;
      let checkedArr = Object.is(checkedKeys.checked, undefined) ? checkedKeys : checkedKeys.checked;
      this.halfCheckedKeys = e.halfCheckedKeys;
      if (checkedArr.length) {
        this.menuSelectStatus = '';
        this.menuSelectHelp = '';
      } else {
        this.menuSelectStatus = 'error';
        this.menuSelectHelp = '请选择相应的权限';
      }
    },
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },
    setFormValues({ ...role }) {
      this.role = role;
      let fields = ['roleName', 'remark'];
      Object.keys(role).forEach(key => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key);
          let obj = {};
          obj[key] = role[key];
          this.form.setFieldsValue(obj);
        }
      });
    },
    handleSubmit() {
      this.$confirm({
        title: '确定保存吗？',
        content: '',
        okText: '保存',
        cancelText: '取消',
        onOk: this.handleConfirmSubmit
      });
    },
    handleConfirmSubmit() {
      let checkedArr = Object.is(this.checkedKeys.checked, undefined) ? this.checkedKeys : this.checkedKeys.checked;
      if (checkedArr.length === 0 && this.halfCheckedKeys.length === 0) {
        this.menuSelectStatus = 'error';
        this.menuSelectHelp = '请选择相应的权限';
      } else {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true;
            let role = this.form.getFieldsValue();
            role.roleId = this.roleInfoData.roleId;
            role.halfCheckedMenuId = !!this.halfCheckedKeys.length ? this.halfCheckedKeys.join(',') : '';
            // checkedArr.push(...this.halfCheckedKeys);
            role.menuId = checkedArr.join(',');
            this.$put('role', {
              ...role
            })
              .then(r => {
                this.reset();
                this.$emit('success');
              })
              .catch(() => {
                this.loading = false;
              });
          }
        });
      }
    }
  },
  watch: {
    roleEditVisiable() {
      if (this.roleEditVisiable) {
        this.$get('menu').then(r => {
          this.menuTreeData = r.data.data.rows.children;
          this.allTreeKeys = r.data.data.ids;
          this.$get('role/menu/' + this.roleInfoData.roleId).then(r => {
            let data = r.data;
            this.defaultCheckedKeys = data.data.map(el => {
              return el.toString();
            });
            // this.halfCheckedMenuId = data.halfIds.map(el => {
            //   return el.toString();
            // });
            this.checkedKeys = data.data.map(el => {
              return el.toString();
            });
            this.expandedKeys = data.data.map(el => {
              return el.toString();
            });

            // this.defaultCheckedKeys = data.menuIds.map(el => {
            //   return el.toString();
            // });
            // this.halfCheckedMenuId = data.halfIds.map(el => {
            //   return el.toString();
            // });
            // this.checkedKeys = data.menuIds.map(el => {
            //   return el.toString();
            // });
            // this.expandedKeys = data.menuIds.map(el => {
            //   return el.toString();
            // });
            this.menuTreeKey = +new Date();
          });
        });
      }
    }
  }
};
</script>
